<template>
  <div class="mod-home">
    <!-- 数据 -->
    <!-- 实时概况板块 -->
    <div class="realtime-situation">
      <!-- 栏目标题行 -->
      <div class="new-page-title">
        <!-- 左边 -->
        <div class="title-left">
          <p class="line" />
          <span class="text">{{ $t("menuList.commodityInsight") }}</span>
        </div>
        <!-- 右边 -->
        <div class="title-right">
          <el-input
            v-model="prodName"
            style="width: 200px"
            :placeholder="$t('dataAnalysis.searchProd')"
            @keyup.enter="onSearch"
          >
            <template #suffix>
              <el-icon
                class="el-input__icon "
                @click="onSearch"
              >
                <Search />
              </el-icon>
            </template>
          </el-input>
        </div>
      </div>
      <!-- /栏目标题行 -->
      <div />
      <!-- 商品概况列表 -->
      <div class="item-list">
        <el-form
          :inline="true"
          :model="dataForm"
          class="form-inline"
          label-width="auto"
          @submit.prevent
        >
          <el-form-item
            :label="$t('dataAnalysis.grouping')"
            class="grouping-status"
          >
            <el-select
              v-model="dataForm.group"
              style="width:120px;height: 15px;"
              :placeholder="$t('dataAnalysis.activeArea')"
              @change="changeDataForm()"
            >
              <el-option
                :label="$t('dataAnalysis.allGroup')"
                :value="0"
              />
              <el-option
                :label="$t('dataAnalysis.hideInList')"
                :value="1"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="$t('product.status')"
            class="grouping-status"
          >
            <el-select
              v-model="dataForm.status"
              style="width:100px;height: 15px;"
              :placeholder="$t('dataAnalysis.activeArea')"
              @change="changeDataForm()"
            >
              <el-option
                :label="$t('dataAnalysis.allStatus')"
                :value="0"
              />
              <el-option
                :label="$t('dataAnalysis.selling')"
                :value="1"
              />
              <el-option
                :label="$t('dataAnalysis.inTheWarehouse')"
                :value="2"
              />
              <el-option
                :label="$t('dataAnalysis.soldOut')"
                :value="3"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div class="title-right">
              <el-select
                v-model="dateValue"
                style="width:100px;height: 15px;"
                @change="onSetDateRange(dateValue)"
              >
                <el-option
                  v-for="item in dateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <span
                v-if="dateValue === 1"
                class="title-time"
              >{{ nowDate }}</span>
              <button
                v-if="dateValue === 1"
                data-v-3baf97fc
                class="el-button el-button--text el-button--small"
                type="button"
                @click="flushDateTime"
              >
                {{ $t('dataAnalysis.refresh') }}
              </button>
              <span
                v-if="dateValue === 2 || dateValue === 3"
                class="title-time"
              >{{ dateRange[0] }} - {{ dateRange[1] }}</span>
            </div>
            <div class="title-picker">
              <el-date-picker
                v-if="dateValue === 4 "
                v-model="dateRange[0]"
                style="width: 150px;"
                type="date"
                :placeholder="$t('dataAnalysis.selectDate')"
                :disabled-date="onDateDisabled"
                :picker-options="PickerOptions"
                @change="onHandleRangeFour()"
              />
            </div>
            <div class="title-picker">
              <el-date-picker
                v-if="dateValue === 5 "
                v-model="preMonth"
                style="width: 150px;"
                type="month"
                :placeholder="$t('dataAnalysis.selectMonth')"
                :picker-options="monthPickerOptions"
                @change="onHandleMonth()"
              />
            </div>
          </el-form-item>
        </el-form>
        <el-form
          :model="form"
          class="form-inline"
          @submit.prevent
        >
          <el-form-item :label="$t('dataAnalysis.saleIndicators')">
            <el-checkbox-group
              v-model="form.saleIndex"
              :max="saleIndicatorsMax"
              @change="selectNumChange"
            >
              <el-checkbox
                :label="$t('dataAnalysis.exposureTimes')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.exposurePeoples')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.addCartNumbers')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.carNumbers')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.placeOrderPerson')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.paidNumbers')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.placeOrderNum')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.goodsPaid')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.placeOrderAmount')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.goodsPaidAmount')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.unitConversionRate')"
                name="saleIndex"
              />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item :label="$t('dataAnalysis.serviceIndicators')">
            <el-checkbox-group
              v-model="form.serviceIndex"
              :max="serviceIndicatorsMax"
              @change="selectNumChange"
            >
              <el-checkbox
                :label="$t('dataAnalysis.refundOrdersCounts')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.applyingForRefund')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.refundedCounts')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.refundedSuccessCounts')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.successfulRefundAmount')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnalysis.refundRate')"
                name="saleIndex"
              />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item
            :label="$t('dataAnalysis.serviceIndicators')"
            class="transparent-text"
          >
            <div
              id="maxSelectSpan"
              class="select-txt"
              style="color:#155bd4 !important;"
            >
              {{ $t("dataAnalysis.upTo8") }}
            </div>
            <div class="select-txt">
              {{ $t("dataAnalysis.selected") }} <span class="select-num-txt">{{ selectNum }}</span>/{{ $t("dataAnalysis.eightItems") }}
            </div>
          </el-form-item>
          <!-- <el-button @click="submitTest">测试</el-button> -->
        </el-form>
        <span />
      </div>
      <!-- /商品概况列表 -->
      <!-- 说明文字板块 -->
      <div class="title-text-info">
        <div>{{ $t("dataAnalysis.descText1") }}{{ $t("dataAnalysis.descText1Content") }}</div>
        <div>{{ $t("dataAnalysis.descText2") }}</div>
      </div>
      <!-- /说明文字板块 -->
      <div class="prod-hid-txt">
        {{ $t("dataAnalysis.hideTips") }}
      </div>
    </div>
    <!-- /实时概况板块 -->
    <!-- 整体看板 -->
    <div class="whole-plate">
      <!-- 图表 -->
      <ProdEffectTable
        :prod-data="prodData"
        style="width: 100%"
      />
      <!-- /图表 -->
      <!-- 分页 -->
      <el-pagination
        v-if="prodData.data.length"
        :current-page="page.pageIndex"
        :page-sizes="[5, 10, 20, 30, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        style="margin-top: 15px"
        layout="total, sizes, prev, pager, next, jumper"
        @update:page-size="sizeChangeHandle"
        @update:current-page="onPageChange"
      />
      <!-- /分页 -->
    </div>
    <!-- /整体看板 -->
  </div>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import ProdEffectTable from './prod-effect-table.vue'
import Big from 'big.js'
import moment from 'moment'

const prodName = ref('')

const nowDate = ref('')
const dateValue = ref(1)
const PickerOptions = reactive({
  disabledDate (time) {
    const date = moment().add(-1, 'days').startOf('day')
    return (
      time.getTime() > date.valueOf()
    )
  }
})
const monthPickerOptions = reactive({
  disabledDate (time) {
    const month1 = moment().startOf('month')
    return (
      time.getTime() > month1.valueOf()
    )
  }
})
const dateOptions = [
  {
    label: $t('dataAnalysis.todayRealTime'),
    value: 1
  },
  {
    label: $t('dataAnalysis.nearly7'),
    value: 2
  },
  {
    label: $t('dataAnalysis.nearly30'),
    value: 3
  },
  {
    label: $t('dataAnalysis.naturalDay'),
    value: 4
  },
  {
    label: $t('dataAnalysis.naturalMonth'),
    value: 5
  }
]
const dateRange = ref([])
const preMonth = ref('') // 前一个月
const dateRange1 = ref([]) // 商品整体概况的时间选择范围
const form = ref({
  saleIndex: [], // 销售指标
  serviceIndex: [] // 服务指标
})
onMounted(() => {
  flushDateTime()
  // 初始选择3个默认数据项
  form.value.saleIndex = [
    $t('dataAnalysis.exposureTimes'),
    $t('dataAnalysis.exposurePeoples')
  ]
  form.value.serviceIndex = [
    $t('dataAnalysis.refundOrdersCounts')
  ]
  selectNumChange()
})
const selectNum = ref(0) // 选择指标的数量
const sumData = ref([])
const prodData = reactive({
  prodName: null, // 商品名称
  dateValue: null, // 时间的选择
  dateRange1: null, // 时间区间
  dataForm: {
    group: null,
    status: null
  }, // 筛选信息
  form: {
    saleIndex: [''], // 销售指标
    serviceIndex: [''] // 服务指标
  }, // 指标选择信息
  sumData: [], // 所有指标
  data: [], // 数据
  params: {
    shopId: null,
    dateType: 1,
    group: 0,
    status: 0,
    prodName: null,
    startTime: null,
    endTime: null
  }
}) // 商品 概况列表
watch(() => form.value.saleIndex, () => {
  selectNum.value = form.value.serviceIndex.length + form.value.saleIndex.length
  prodData.form = form.value
  sumData.value = []
  sumData.value = sumData.value.concat(form.value.serviceIndex).concat(form.value.saleIndex)
  prodData.sumData = sumData.value
})
watch(() => form.value.serviceIndex, () => {
  selectNum.value = form.value.saleIndex.length + form.value.serviceIndex.length
  prodData.form = form.value
  sumData.value = []
  sumData.value = sumData.value.concat(form.value.serviceIndex).concat(form.value.saleIndex)
  prodData.sumData = sumData.value
})
/**
 * 刷新时间
 */
const page = ref({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 5 // 每页显示多少条
})
const flushDateTime = () => {
  const date = moment()
  nowDate.value = date.format('LL')
  dateRange1.value = [moment(date).startOf('days').format('LL'), nowDate.value]
  prodData.dateRange1 = dateRange1.value
  onGetProdEffect(page.value)
}
// 对可选日进行判断
const onDateDisabled = (time) => {
  return time.getTime() > moment().add(-1, 'days').valueOf() // 之后不可选
}
/**
 * 1:今天 2: 近七天 3:近30天 4:昨天 5:自然月(前一个月如当前月为7月，自然月为6月)
 */
let startDay = null
let endDay = null
const onSetDateRange = (val) => {
  prodData.dateValue = val
  if (val === 1) {
    startDay = 0
    endDay = 0
    dateRange1.value = [moment().startOf('days').format('LL'), nowDate.value]
    prodData.dateRange1 = dateRange1.value
    onGetProdEffect(page.value)
    return
  } else if (val === 2) {
    startDay = -6
    endDay = 0
  } else if (val === 3) {
    startDay = -29
    endDay = 0
  } else if (val === 4) {
    startDay = 0
    endDay = 0
  } else if (val === 5) {
    preMonth.value = onGetPreMonth()
    return
  } else {
    return
  }
  const time = moment().add(-1, 'days')
  // 开始时间
  const startTime = moment(time).add(startDay, 'days')
  // 结束时间
  const endTime = moment(time).add(endDay, 'days')
  dateRange.value = [startTime.format('L'), endTime.format('L')]
  dateRange1.value = [startTime.startOf('days').format('LL'), endTime.endOf('days').format('LL')]
  prodData.dateRange1 = dateRange1.value
  onGetProdEffect(page.value)
}
/**
 * 获取前一个月的时间
 */
const onGetPreMonth = (date) => {
  if (!date) {
    date = new Date()
  }
  // 月的开始时间
  const timeStar = moment(date).startOf('month')
  // 月的结束时间
  const timeEnd = moment(timeStar).endOf('month')
  dateRange1.value = [timeStar.format('LL'), timeEnd.format('LL')]
  prodData.dateRange1 = dateRange1.value
  onGetProdEffect(page.value)
  return moment(date).format('L')
}
/**
 * 当dateRange == 4 监听dateRange[0]的变化
 */
const onHandleRangeFour = () => {
  const date = dateRange.value[0]
  if (date) {
    const d = moment(date).startOf('days')
    dateRange1.value = [d.format('LL'), moment(d).endOf('days').format('LL')]
    prodData.dateRange1 = dateRange1.value
  } else {
    dateRange1.value = ['1971-01-01 00:00:00', '1971-01-01 00:00:00']
    prodData.dateRange1 = dateRange1.value
  }
  onGetProdEffect(page.value)
}
/**
 * 当dateRange == 5 监听dateRange[0]的变化
 */
const onHandleMonth = () => {
  if (preMonth.value) {
    onGetPreMonth(preMonth)
  } else {
    dateRange1.value = ['1971-01-01 00:00:00', '1971-01-01 00:00:00']
    onGetProdEffect(page.value)
  }
}
/**
 * 获取商品概况数据
 */
const dataForm = ref({
  group: 0,
  status: 0
})
const onGetProdEffect = (pageParam) => {
  // 请求参数传给表格子组件
  const params = {}
  params.shopId = null
  params.dateType = dateValue.value
  params.group = dataForm.value.group
  params.status = dataForm.value.status
  params.prodName = prodName.value
  params.startTime = dateRange1.value[0]
  params.endTime = dateRange1.value[1]
  prodData.params = params
  http({
    url: http.adornUrl('/admin/prodAnalysis/getProdEffect'),
    method: 'get',
    params: http.adornParams(
      {
        current: pageParam.currentPage,
        size: pageParam.pageSize,
        shopId: null,
        dateType: dateValue.value,
        group: dataForm.value.group,
        status: dataForm.value.status,
        prodName: prodName.value,
        startTime: dateRange1.value[0],
        endTime: dateRange1.value[1]
      }
    )
  }).then(({ data }) => {
    if (data) {
      data.records.forEach(element => {
        if (element.singleProdRate > 0) {
          Big.DP = 2
          element.singleProdRate = new Big(element.singleProdRate).times(100).toFixed()
          element.refundSuccessRate = new Big(element.refundSuccessRate).times(100).toFixed()
        }
      })
      prodData.data = data.records
      page.value.total = data.total
    }
  })
}
/**
 * 搜索商品名称
 */
const onSearch = () => {
  onGetProdEffect(page.value)
}
// 每页数
const sizeChangeHandle = (val) => {
  page.value.pageSize = val
  page.value.currentPage = 1
  onGetProdEffect(page.value)
}
// 当前页
const onPageChange = (val) => {
  page.value.currentPage = val
  onGetProdEffect(page.value)
}
/**
 * 选择框改变
 */
const changeDataForm = () => {
  prodData.dataForm = dataForm.value
  onGetProdEffect(page.value)
}

/**
 * 动态修改最大可选数
 */
const serviceIndicatorsMax = ref(8) // 服务指标最大可选
const saleIndicatorsMax = ref(8) // 销售指标最大可选

const selectNumChange = () => {
  const num = 8 - (form.value.saleIndex.length + form.value.serviceIndex.length)
  if (num <= 0) {
    saleIndicatorsMax.value = form.value.saleIndex.length
    serviceIndicatorsMax.value = form.value.serviceIndex.length
  } else {
    saleIndicatorsMax.value = 8
    serviceIndicatorsMax.value = 8
  }
}

</script>

<style lang="scss" scoped>
.mod-home {
  .transparent-text ::v-deep(.el-form-item__label) {
    color: transparent;
  }
  div ::v-deep(.el-input__inner) {
    border-radius: 3px;
  }
  .grouping-status :deep(.el-form-item__label){
    padding-top: 8px;
  }
  :deep(.el-form-item)  {
    margin-bottom: 20px;
  }
  .item-list {
    background: #F7F8FA;
    margin: 20px 0 20px;
    padding-top: 20px;
    padding-bottom: 10px;
  }
  .form-inline {
    margin-left: 20px;
  }
  .title-text-info {
    background: rgba(246, 192, 35, 0.06);
    border: 1px solid #F6C023;
    padding: 18px;
  }
  .title-left {
    text-align: left;
    display: flex;
    align-items: center;
    width: 80%;
  }
  .title-right {
    text-align: right;
    display: inline;
    line-height: 1;
  }
  .title-picker {
    display: inline;
  }
  .title-time {
    color: #999999;
    display: inline-block;
    margin-top: 15px;
    vertical-align: middle;

  }
  :deep(.el-button--small){
    margin-top: 15px;
  }
  /**
  整体看板
   */
  .whole-plate {
    margin: 15px 0 30px;

  }

  /**
  退款看板
   */
  .title-text-info div {
    font-size: 12px;
    line-height: 18px;
    color: #666;
    &:first-child {
      margin-bottom: 12px;
    }
  }
  .select-txt:first-child {
    color: #155bd4;
  }
  .select-txt {
    font-size: 12px;
    color: #999999;
    display: inline-block;
  }
  .select-num-txt {
    color: #155BD4;
  }
  .prod-hid-txt {
    margin-top: 25px;
    font-size: 12px;
    color: #666666;
  }
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper){
    padding-top: 9px;
  }
}
</style>
